package com.lym.echo.controller;

import com.google.code.kaptcha.Producer;
import com.lym.echo.entity.User;
import com.lym.echo.service.UserService;
import com.lym.echo.util.CommunityConstant;
import com.lym.echo.util.CommunityUtil;
import com.lym.echo.util.RedisKeyUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author Liym on 2021/8/28
 * 登录、注册、登出
 */
@Controller
@Slf4j
public class LoginController {

    @Resource
    private UserService userService;

    @Resource
    private Producer kaptchaProducer;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 进入注册页面
     *
     * @return
     */
    @GetMapping(value = "/register")
    public String getRegisterPage() {
        return "site/register";
    }

    /**
     * 进入登录界面
     *
     * @return
     */
    @GetMapping("/login")
    public String getLoginPage() {
        return "site/login";
    }


    /**
     * 进入重置密码界面
     */
    @GetMapping("/resetPwd")
    public String getResetPwdPage() {
        return "site/reset-pwd";
    }

    @PostMapping("/register")
    public String register(Model model, User user) {
        Map<String, Object> map = userService.register(user);
        if (map == null || map.isEmpty()) {
            model.addAttribute("msg", "注册成功, 我们已经向您的邮箱发送了一封激活邮件，请尽快激活!");
            model.addAttribute("target", "index");
            return "/site/operate-result";
        } else {
            log.info("当前用户注册信息为{}", user);
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            model.addAttribute("emailMsg", map.get("emailMsg"));
            return "/site/register";
        }
    }

    /**
     * @param model
     * @param userId
     * @param code
     * @return http:localhost:18080/echo/activation/用户id/激活码
     */
    @GetMapping("/activation/{userId}/{code}")
    public String activation(Model model, @PathVariable("userId") int userId,
                             @PathVariable("code") String code) {
        int result = userService.activation(userId, code);
        if (result == CommunityConstant.ACTIVATION_SUCCESS) {
            model.addAttribute("msg", "激活成功, 您的账号已经可以正常使用!");
            model.addAttribute("target", "/login");
        } else if (result == CommunityConstant.ACTIVATION_REPEAT) {
            model.addAttribute("msg", "无效的操作, 您的账号已被激活过!");
            model.addAttribute("target", "index");
        } else {
            model.addAttribute("msg", "激活失败, 您提供的激活码不正确!");
            model.addAttribute("target", "index");
        }
        return "/site/operate-result";
    }

    /**
     * Kaptcha 生成验证码
     *
     * @param response
     */
    @GetMapping("/kaptcha")
    public void getKaptcha(HttpServletResponse response) {
        //生成验证码
        String text = kaptchaProducer.createText();
        log.info("验证码为:" + text);
        //生成验证码图片
        BufferedImage image = kaptchaProducer.createImage(text);
        //验证码的归属者
        String kaptchaOwner = CommunityUtil.generateUUID();
        Cookie cookie = new Cookie("kaptchaOwner", kaptchaOwner);
        cookie.setMaxAge(60);
        cookie.setPath(contextPath);
        response.addCookie(cookie);
        // 将验证码存入 redis
        String kaptchaKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
        redisTemplate.opsForValue().set(kaptchaKey, text, 60, TimeUnit.SECONDS);
        //将图片输出给浏览器
        response.setContentType("image/png");
        try {
            ServletOutputStream outputStream = response.getOutputStream();
            ImageIO.write(image, "png", outputStream);
        } catch (IOException e) {
            log.error("响应验证码失败:{}", e);
        }
    }

    /**
     * 验证用户输入验证码是否和redis中存入的相等
     *
     * @param kaptchaOwner 验证码所属者
     * @param checkCode    用户输入的验证码
     * @return
     */
    private String checkKaptchaCode(String kaptchaOwner, String checkCode) {
        if (StringUtils.isBlank(checkCode)) {
            log.info("未发现输入的图片验证码");
            return "未发现输入的图片验证码";
        }
        String kaptchaKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
        String kaptchaValue = (String) redisTemplate.opsForValue().get(kaptchaKey);
        if (StringUtils.isBlank(kaptchaValue)) {
            log.info("图片验证码过期");
            return "图片验证码过期";
        }
        if (!kaptchaValue.equals(checkCode)) {
            log.info("验证码输入错误");
            return "验证码输入错误";
        }
        return "";
    }

    /**
     * 用户登录
     *
     * @param username     用户名
     * @param password     密码
     * @param code         验证码
     * @param rememberMe   是否记住我（点击记住我后，凭证的有效期延长）
     * @param model
     * @param response
     * @param kaptchaOwner 从 cookie 中取出的 kaptchaOwner
     * @return
     */
    @PostMapping("/login")
    public String login(@RequestParam("username") String username, @RequestParam("password") String password,
                        @RequestParam("code") String code, @RequestParam(value = "rememberMe", required = false) boolean rememberMe,
                        Model model, HttpServletResponse response,
                        @CookieValue("kaptchaOwner") String kaptchaOwner) {
        //检查验证码
        String kaptcha = "";
        if (!StringUtils.isBlank(kaptchaOwner)) {
            String kaptchaKey = RedisKeyUtil.getKaptchaKey(kaptchaOwner);
            kaptcha = (String) redisTemplate.opsForValue().get(kaptchaKey);
        }
        if (StringUtils.isBlank(kaptcha) || StringUtils.isBlank(code) || !code.equalsIgnoreCase(kaptcha)) {
            model.addAttribute("codeMsg", "验证码错误");
            return "/site/login";
        }
        // 凭证过期时间（是否记住我）
        int expiredSeconds = rememberMe ? CommunityConstant.REMEMBER_EXPIRED_SECONDS : CommunityConstant.DEFAULT_EXPIRED_SECONDS;
        //验证用户
        Map<String, Object> map = userService.login(username, password, expiredSeconds);
        if (map.containsKey("ticket")) {
            // 账号和密码均正确，则服务端会生成 ticket，浏览器通过 cookie 存储 ticket
            Cookie cookie = new Cookie("ticket", map.get("ticket").toString());
            cookie.setPath(contextPath);    //cookie有效范围
            cookie.setMaxAge(expiredSeconds);
            response.addCookie(cookie);
            return "redirect:index";
        } else {
            model.addAttribute("usernameMsg", map.get("usernameMsg"));
            model.addAttribute("passwordMsg", map.get("passwordMsg"));
            return "/site/login";
        }
    }



}
